<?php
include_once ("dblib.php");


/**
 * The purpose of this class is to handle elements on our structure for being able to store nodes correctly.
 * @author CEPAL.
 * @package ElementHandler
 */
class ElementHandler{

    private $tableName;
    private $separadorIds;
    private $elements_name_regex;
    private $nombreRaiz;
    /**
     * Constructor
     * @param <type> $nombreTabla
     * @param bool $debug true for debug messages
     */
    function __construct($nombreTabla,$parametros,$debug=false){
        $this->separadorIds=$parametros['id_char'];
        $this->tableName=$nombreTabla;
        $this->nombreRaiz=$parametros['root_name'];
        $this->elements_name_regex=$parametros['elements_name_regex'];
        if($debug){
            $mensaje="->TableName:$nombreTabla.<>
            IdsSep: $this->separadorIds. <>Root: $this->nombreRaiz.<-";
            trigger_error($mensaje,E_USER_NOTICE);
        }
    }

    private function validateName($name){
        return(preg_match($this->elements_name_regex,$name)>0);
    }
   

    /**
     * This function insert an element into the element table.
     * @param string $type type of the element to insert
     * @param string $name name of the element to insert
     * @param StructHandler Object of StructHandler Class.
     * @param bool $debug true for debug messages.
     * @return integer It returns the id assigned to the element or -1 if it can not be inserted.
     */
    public function insert($type,$name,$shObject, $debug=false){
        if($debug){$mensaje=array();}
        $nombreTabla=$this->tableName;
        if(!$shObject->isElementName($type)){
            if($debug){
                $mensaje[]="Element: |$name|, type: |$type| can not be inserted. Function will return -1.";
            }
            $resultado=-1;
        }
        else{
            if(!$this->validateName($name)){
                if($debug){
                    $mensaje[]="Element: $name, type: $type can not be inserted. Function will return -1.";
                }
                $resultado=-1;
            }
            else{
                $query="INSERT INTO ".$nombreTabla." (type,name) VALUES ('".$type."','".$name."')";
                $result=DB::query($query);
                if($result) {
                    $query="SELECT id FROM ".$nombreTabla." WHERE name='".$name."' AND type='".$type."'";
                    $result2=DB::query($query);
                    $row=DB::fetch_assoc($result2);
                    if($debug){
                        $mensaje[]="Element: $name, type: $type has been inserted with id:".$row['id'];
                    }
                    $resultado= $row['id'];
                }else {
                    if($debug){
                        $mensaje[]="Element: $name, type: $type can not be inserted. Function will return -1.";
                    }
                    $resultado=-1;
                }
            }
        }
        if($debug){
            foreach($mensaje as $mens){
                trigger_error($mens,E_USER_NOTICE);
            }
        }
        return $resultado;
    }


    /**
     * This function returns the type of an element on the table
     * @param <type> $elementid ID of the element to return
     * @return <type>  type of the element returned.
     */
    private function getTypeId($elementid){
        $nombreTabla=$this->tableName;
        $query="SELECT type FROM ".$nombreTabla." WHERE id=".$elementid;
        $result=DB::query($query);
        if(DB::num_rows($result)==0) return -1; //Elemento no existe
        $row=DB::fetch_assoc($result);
        return $row['type'];
    }



    /**
     *  Check if an element exists on the table or not.
     * @param <type> $name Name of the element to check
     * @return <type> true is exists, false otherwise.
     */
    public function exists($name){
        $nombreTabla=$this->tableName;
        $n=explode($this->separadorIds,$name);
        if (count ($n)>1) {
            $query="SELECT count(*) FROM ".$nombreTabla." WHERE id=".$n[1]." AND type='".$n[0]."'";
            $result=DB::query($query);
            if(!$result)return false;
            if(DB::num_rows($result)>0){
                $row=DB::fetch_assoc($result);
                if($row['count(*)']==0) return false; //Elemento no existe
                else return true;
            }else return false;
        }
        else {
            return false;
        }
     }


    /**
     *This function returns the id of an element with a given name
     * @param <type> $name Name of the element to return.
     * @return <type> id of the returned node.
     */
    public function getId($name,$type){
        /*
        $nombreTabla=$this->tableName;
        $n=explode($this->separadorIds,$name);
        if (count ($n)>1) {
            $query="SELECT id FROM ".$nombreTabla." WHERE id=".$n[1]." AND type='".$n[0]."'";
            $result=DB::query($query);
            if(!$result)return -1;
            if(DB::num_rows($result)>0){
                $row=DB::fetch_assoc($result);
                return $row['id'];
            }else return -1;
        }
        else {
            return -1;
        }*/
        $nombreTabla=$this->tableName;
        $query="SELECT id FROM ".$nombreTabla." WHERE name='".$name."' AND type='".$type."'";
            $result=DB::query($query);
            if(!$result)return -1;
            if(DB::num_rows($result)>0){
                $row=DB::fetch_assoc($result);
                return $row['id'];
            }else return -1;
    }


    /**
     * Function that deletes the element named $name and its data.
     * @param string $name
     * @return boolean true if any row has been deleted.
     */
    public function delete($name,$debug=false){
        $nombreTabla=$this->tableName;
        $n=explode($this->separadorIds,$elementName);
        if (count ($n)>1) {
            $query="DELETE FROM ".$nombreTabla." WHERE id=".$n[1]." AND type='".$n[0]."'";
            $result=DB::query($query);
            if($result){
                if($debug)trigger_error("Element ".$name." has been deleted. Function will return true.",E_USER_NOTICE);
                return true;

            }else {
                if($debug)trigger_error("Element ".$name." can not be deleted. Function will return false.",E_USER_NOTICE);
                return false;
            }
        }
        else {
            if($debug)trigger_error("Element ".$name." can not be deleted. Function will return false.",E_USER_NOTICE);
            return false;
        }
    }
}
?>
